package cn.edu.laud.sany.datatest;

import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import cn.edu.laud.sany.datatest.RandomKeys.Iterm;
import cn.edu.laud.sany.utils.TimeUtils;

public class Master
{
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		if (args.length < 3)
		{
			System.out.println("need params");
			return;
		}
		String[] hosts = args[0].split(",");
		Integer port = Integer.valueOf(args[1]);
		String keyspace = args[2];
		Master.keyspace = keyspace;
		int type = Integer.valueOf(args[3]);
		BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
		ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1,
				TimeUnit.DAYS, queue);
		long time = System.nanoTime();
		for (int i = 0; i < 1; i++)
		{
			executor.execute(new ThreadWorker(i, hosts[i % 2], port, type));
		}
		executor.shutdown();
		try
		{
			executor.awaitTermination(1000, TimeUnit.DAYS);
		}
		catch (InterruptedException e1)
		{
			e1.printStackTrace();
		}
		System.err.println("program cost:"
				+ TimeUtils.nanoSecondToString(System.nanoTime() - time));
		if (type == 1)
			System.err.println("total time cost:"
					+ TimeUtils.nanoSecondToString(result));
		else
			System.err.println("total number :" + result);
	}
	
	private static File superfolder = new File("keys");
	private static ConcurrentLinkedQueue<File> files = new ConcurrentLinkedQueue<File>();
	public static String keyspace = "laud_sany_equipworkrec";
	static
	{
		for (File folder : superfolder.listFiles())
		{
			// System.out.println(folder.getName());
			if (folder.isDirectory())
			{
				for (File file : folder.listFiles())
				{
					files.add(file);
				}
			}
		}
	}
	public static long result = 0;
	
	public static File askForACountJob(Integer no)
	{
		return files.poll();
	}
	
	public static List<Iterm> askForAReadJob(Integer no)
	{
		List<Iterm> list = RandomKeys.getRandomKeys(
				"keys/moreThan1000/cf_gk_285", 1000 + "");
		return list;
	}
	
	public synchronized static void commitResult(Integer no, long res)
	{
		result += res;
	}
	
}
